package com.jwt.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jwt.demo.entity.User;

import java.util.Date;

/**
 * @ClassName: TokenUtil
 * @Description: TokenUtil
 * @Author zhouzhixin
 * @Date 2021/8/30
 * @Version 1.0
 */
public class TokenUtil {

    // token到期时间10小时
    private static final long EXPIRE_TIME = 60   * 60 * 1000;
    // 密钥盐
    private static final String TOKEN_SECRET = "mrzhou**abcdefg??";

    /**
     * <p>生成token</p>
     *
     * @param user
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/8/30 11:09
     */
    public static String sign(User user) {

        String token = null;
        try {
            Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            token = JWT.create()
                    .withIssuer("auth0")//发行人
                    .withClaim("username", user.getUsername())//存放数据
                    .withExpiresAt(expireAt)//过期时间
                    .sign(Algorithm.HMAC256(TOKEN_SECRET));
        } catch (IllegalArgumentException | JWTCreationException ignored) {

        }
        return token;
    }


    /**
     * <p>认证token</p>
     *
     * @param token
     * @return java.lang.Boolean
     * @author zhouzhixin
     * @date 2021/8/30 11:09
     */
    public static Boolean verify(String token) {

        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();//创建token验证器
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            System.out.println("认证通过：");
            System.out.println("username: " + decodedJWT.getClaim("username").asString());
            System.out.println("过期时间：" + decodedJWT.getExpiresAt());
        } catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            return false;
        }
        return true;
    }

}
